<template>
  <div class="zs-table-page-container">
    <div class="zs-card-sm zs-space-bottom zs-layout-flex-row zs-layout-justify-between">
      <span>
        <el-select @change="queryList" v-model="queryParams.biProjectCode" filterable clearable
          class="zs-select-md zs-space-right-sm" placeholder="项目名称">
          <el-option v-for="item in querySelectList.projectList" :key="item.biProjectCode" :label="item.biProjectName"
            :value="item.biProjectCode" />
        </el-select>
        <el-date-picker @change="queryList" class="zs-space-right-sm" v-model="queryParams.yearmonth" type="month"
          placeholder="日期" :clearable="false" value-format="YYYY-MM" :prefix-icon="DateBeforeIcon" />
        <el-select @change="queryList" v-model="queryParams.benchmarkFlag" class="zs-select-md zs-space-right-sm"
          placeholder="口径">
          <el-option v-for="item in querySelectList.caliberList" :key="item.dictValue" :label="item.dictLabel"
            :value="item.dictValue" :disabled="queryParams.projectType == '3' && item.dictValue == '1'" />
        </el-select>
        <el-popover popper-class="zs-popper" placement="bottom-end" trigger="click">
          <template #reference>
            <el-button class="zs-btn-square-solid" :class="{ 'zs-btn-square-solid-active': true }">
              <el-icon>
                <MoreFilled />
              </el-icon>
            </el-button>
          </template>
          <template #default>
            <el-select @change="queryList" v-model="queryParams.productLine" class="zs-select-md zs-space-right-sm"
              filterable placeholder="产品线" clearable>
              <el-option v-for="item in querySelectList.productLine" :key="item.code" :label="item.name"
                :value="item.code" />
            </el-select>
            <el-cascader placeholder="城市" @change="queryList" :teleported="false" :show-all-levels="false"
              ref="cascaderRef" v-model="queryParams.cityCode" :options="citys" :props="cascaderProp" clearable
              class="zs-select-md zs-space-right-sm" />
          </template>
        </el-popover>
        <el-button @click="queryList" class="zs-btn-plain">查询</el-button>
      </span>
      <span>
        <el-button v-for="item, index in querySelectList.modelList" :key="index" @click="modelChange(item)"
          :class="[queryParams.projectType == item.dictValue ? 'zs-btn-primary' : 'zs-btn-info', index == querySelectList.modelList.length - 1 ? 'zs-space-right-min' : '']">{{
          item.dictLabel
          }}</el-button>
        <el-button class="zs-btn-plain" @click="handleDownload"
          v-btnPermi="{ permi:'p_btn_budget_two_one_control_listexport'}">
          <el-icon class="el-icon--left">
            <Upload />
          </el-icon>导出
        </el-button>
      </span>
    </div>
    <div class="zs-card zs-table-page-content">
      <hsPageTable :isHavePage="false" :loading="tableData.loading" :tableData="tableData.data"
        :cloumns="tableData.cloumns" :cellClassName="tableData.cellClassFn" indexFixed :headerCellClass="tableData.heightClassFn">
        <template #column>
          <el-table-column label-class-name="zs-table-cell-border-left" v-for="item, index in tableData.firstHeaderArr"
            :label="item.label" :key="index" align="center">
            <el-table-column
              :label-class-name="tableData.budgetKey.includes(childrenItem.prop) ? 'zs-table-cell-border-left' : ''"
              v-for="childrenItem in item.children" :label="childrenItem.label" :key="childrenItem.prop"
              :width="childrenItem.width" align="right">
              <template #default="{ row }">
                <span :class="{'zs-text-red':row[childrenItem.prop+'Color'] == 1,'zs-text-orange':row[childrenItem.prop+'Color'] == 2,'zs-text-green':row[childrenItem.prop+'Color'] == 3}">{{ valInIt(row[childrenItem.prop],  childrenItem.prop) }}</span>
              </template>
            </el-table-column>
          </el-table-column>
        </template>
      </hsPageTable>
    </div>
  </div>
</template>

<script setup>
// import PageTable from "@/components/page-table.vue"
import { queryReportListApi, queryProductLineByBizTypeApi, queryAllProjectListApi, exportReportApi } from '@/api/TwoControlReport'
import dbPublicApi from '@/api/dbPublic';
import { downloadNewFile } from '@/utils/publicUtils'
import { reactive, shallowRef, h } from "vue"
import { useRouter } from 'vue-router'
import { useStore } from "vuex";
let store = useStore();
let router = useRouter();

const DateBeforeIcon = shallowRef({
  render () {
    return h('span', { style: { 'font-size': '12px' } }, '截至')
  },
})

// 数据字典数据
const dictObj = store.getters.getDictObj(['PROJECT_COMMERCIAL_ACTIVITIES', 'INVESTOR', 'PROJECT_STAGE'])
// 业态字典对象
let biztypeDict = {};
dictObj.PROJECT_COMMERCIAL_ACTIVITIES.forEach((bizType) => {
  biztypeDict[bizType.dictValue] = bizType;
})
// 集团字典表格转换
let investorDict = {};
dictObj.INVESTOR.forEach((ele) => {
  investorDict[ele.dictValue] = ele;
})
// 阶段字典转换
let stageDictObj = {}
dictObj.PROJECT_STAGE.forEach(el => {
  stageDictObj[el.dictValue] = el
})
// 城市数据
let citys = JSON.parse(localStorage.getItem('addrTree')).list
citys.forEach(el => {
  el.child = el.childList
})
// 城市props
let cascaderProp = {
  children: 'child',
  label: 'name',
  value: 'code',
  emitPath: false,
  // multiple: true 
}

// 查询条件
let queryParams = reactive({
  projectType: '0',
  biProjectCode: '',
  productLine: '',
  cityCode: '',
  yearmonth:'',
  benchmarkFlag: '0'
})


let querySelectList = reactive({
  productLine: [],
  projectList: [],
  caliberList: [
    { dictLabel: '预算对标', dictValue: '0' },
    { dictLabel: '标准对标', dictValue: '1' }, 
  ],
  modelList: [
    { dictLabel: '商业', dictValue: '0' },
    { dictLabel: '产办', dictValue: '1' },
    { dictLabel: '厂房', dictValue: '2' },
    { dictLabel: '酒寓', dictValue: '3' },
    { dictLabel: '轻资产', dictValue: '4' },
    { dictLabel: '其他', dictValue: '5' },
  ],
})

// let queryPopoverParamsSelect = computed(()=>{
//   let flg = false
//   let outKey = ['biProjectCode','projectType','productLine','cityCode']
//   for(let key in queryParams) {
//     if (!outKey.includes(key) && queryParams[key] != '') {
//       flg = true
//       break
//     }
//   }
//   return flg
// })
// 表格数据
let tableData = reactive({
  updateDate:'',
  loading: false,
  budgetKey: [],
  data: [],
  total: 0,
  firstHeaderArr: [],
  // secondHeaderArr:[{label:'预算',key:'Budget'},{label:'实际',key:'Actual'},{label:'实际',key:'Conclusion'}],
  cloumns: [
    { prop: 'projectName', label: '项目名称', align: 'left', width:'210', fixed:'left', type:'html', render({row}){
      return <span class="zs-link" onClick={()=>jumpDetail(row)}>{row.projectName}</span>
    } },
    { prop: 'formatName', label: '业态', width: "100" },
    { prop: 'productLineName', label: '产品线', width: "130", align:'left' },
    // { prop:'phase',label:'阶段',type:'dict',width:"110", currentDict:stageDictObj },
    // { prop:'investor',label:'集团',type:'dict', width:'110', currentDict:investorDict,multiple:{flg:true} },
    { prop: 'cityName', label: '城市', width: '100' },
  ],
  cellClassFn: setCellCalss,
  heightClassFn: setCellCalss,
})

function setCellCalss ({ column }) {
  if (tableData.budgetKey.includes(column.rawColumnKey) || column.rawColumnKey == 'formatName') {
    return 'zs-table-cell-border-left'
  }
}

function valInIt(val, key) {
  if (key == 'empty') return ''
  let curVal = val
  if (val) {
    if (/\d+/g.test(val)) {
      curVal = Number(val.replace('%','')).toFixed(1) + '%'
    }
  } else {
    curVal = '-'
  }
  return curVal
}

function queryList () {
  tableData.loading = true
  queryReportListApi(queryParams).then(res => {
    let resData = res.data
    if (resData.code == 200) {
      if (resData.data.header.length > 0) {
        let budgetKey = []
        resData.data.header.splice(0, 5)
        // let setName = new Set()
        let obj = {}
        resData.data.header.forEach(el => {
          el.width = '120'
          if (obj[el.name]) {
            obj[el.name].children.push(el)
          } else {
            obj[el.name] = { label: el.name, children: [el] }
            budgetKey.push(el.prop)
          }
        })
        let firstHeaderArr = []
        for (var key in obj) {
          firstHeaderArr.push(obj[key])
        }
        if (resData.data.header.length <= 6) {
          firstHeaderArr.push({label:'',children:[{prop:'empty',label:''}]})
          budgetKey.push('empty')
        }
        tableData.firstHeaderArr = firstHeaderArr
        tableData.budgetKey = budgetKey
      } else {
        tableData.firstHeaderArr = [{ label: '' }]
      }
      tableData.data = resData.data.bodyList
      tableData.updateDate = resData.data.yeartime
      setTimeout(()=>{
        tableData.loading = false
      },1000)
    }
  })
}
function queryDataUpdateTime() {
  dbPublicApi.queryMonthsTimeApi().then(res=>{
    let resData = res.data
    if(resData.code == 200){
      queryParams.yearmonth = resData.data
      queryList()
    }
  })
}
queryDataUpdateTime()

function getProductLineData () {
  queryProductLineByBizTypeApi('COMMERCIAL,OFFICE,INDUSTRIAL,HOTEL,APARTMENT').then(res => {
    let resData = res.data
    if (resData.code == 200) {
      console.log(resData.data);
      let curProductLine = []
      resData.data.forEach(el => {
        curProductLine.push(...el.list)
      })
      querySelectList.productLine = curProductLine
    }
  })
}
getProductLineData()


function modelChange (item) {
  queryParams.projectType = item.dictValue;
  if (item.dictValue == '3') {
    queryParams.benchmarkFlag = '0'
  }
  queryList()
}

function queryAllProject() {
  queryAllProjectListApi().then(res=>{
    let resData = res.data
    if(resData.code == 200){
      // console.log('项目',resData.data);
      querySelectList.projectList = resData.data || []
    }
  })
}
queryAllProject()

async function handleDownload() {
  const fileName = `两算一控报表.xls`
  let fileData
  await exportReportApi(queryParams).then(res => {
    fileData = res.data
  })
  downloadNewFile(fileData, fileName)
}


function jumpDetail(row) {
  router.push({
    path: '/page/routeController/index',
    query: {
      rid: 'Manage_Business_TwoControl_Detail',
      rTitle: '两算一控明细',
      biProjectCode: row.biProjectCode,
      updateDate: tableData.updateDate,
      tabPermi: 'p_btn_901_jingyingxiangmu_shangye',
      projectName: row.projectName,
      bizType: row.formatCode,
      yearMonth: queryParams.yearmonth,
      cardLabel:queryParams.benchmarkFlag
    },
  })
}
</script>

<style lang="scss" scoped>
:deep(.el-table--group .el-table__cell) {
  border-right: none !important;
}

:deep(.el-table--border::after),
:deep(.el-table--border::before) {
  width: 0;
}

:deep(.el-table__border-left-patch) {
  background-color: transparent;
}

:deep(.el-table__row .zs-link){
  cursor: pointer !important;
}
:deep(.el-table--group .el-table__inner-wrapper tr:first-child td:first-child){
  border-left:none;
}
</style>
